<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class GoCarController extends Controller
{
	public function getIndex(Request $request)
	{
		if($request['name']){
			$goinfo = DB::table('gocar')
			->join('department','department.DepartmentId','=','gocar.DepartmentId')
			->join('vehicle','vehicle.id','=','gocar.CarNumber')
			->select('gocar.id','gocar.GoTime','gocar.Destination','gocar.Reason','department.DepartmentName','vehicle.CarClass','vehicle.CarNum')
			->where('CarNumber','like','%'.$request['name'].'%')
            ->paginate(10);
		}else{
			$goinfo = DB::table('gocar')
			->join('department','department.DepartmentId','=','gocar.DepartmentId')
			->join('vehicle','vehicle.id','=','gocar.CarNumber')
			->select('gocar.id','gocar.GoTime','gocar.Destination','gocar.Reason','department.DepartmentName','vehicle.CarClass','vehicle.CarNum')
			->paginate(3);
		}
		// dd($goinfo);				
		 $info = $request -> all();
		return view('Lzk.Gocar.Gocar',['goinfo'=>$goinfo,'info'=>$info]);
	}

	//解析添加
	public function getAdd()
	{
		$pinfo = DB::table('department')->get();
		$cnum = DB::table('vehicle')->where('State',1)->get();
		// dd($cnum);
		// dd($pinfo);
		return view('Lzk.GoCar.AddGoCar',['pinfo'=>$pinfo,'cnum'=>$cnum]);
	}
	//执行添加
	public function postInsert(Request $request)
	{
		// dd($request->all());
		$ins = $request->only('DepartmentId','CarNumber','GoTime','Destination','Reason','Mileage');
		// dd($ins);
		$id = $ins['CarNumber'];
		$ins['Date'] = time();
		$res = DB::table('gocar')->insert($ins);
		if($res){
				// dd($cinfo);
				DB::select("update vehicle set State = 2 where id = {$id}");
				return redirect('/GoCar');
				
			}else{
				return back();
			}
	}

	//删除
	public function getDel($id)
	{

		$info = DB::table('gocar')->where('id',$id)->get();
		$vinfo = DB::table('vehicle')->where('id',$info[0]['CarNumber'])->get();
		// dd($vinfo);
		$vid = $vinfo[0]['id'];
		// dd($vid);

		$res = DB::table('gocar')->where('id',$id)->delete();
		if($res){
			DB::select("update vehicle set State = 1 where id = {$vid}");
			return redirect('/GoCar');
		}else{
			return back();
		}
	}

}